package com.cheer.controller;

import com.cheer.bo.LotteryBO;
import com.cheer.common.Result;
import com.cheer.service.AuthService;
import com.cheer.service.LotteryService;
import com.cheer.vo.ExMatchUserVO;
import com.cheer.vo.LotteryRecordVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author cheer
 */
@RestController
@RequestMapping("/lottery")
@Slf4j
public class LotteryController {

    @Autowired
    private LotteryService lotteryService;

    @Autowired
    private AuthService authService;

    @GetMapping("/announcement")
    public Result<List<String>> getLotteryAnnouncement() {
        return Result.success(lotteryService.getLotteryAnnouncement());
    }

    @GetMapping("/start")
    public Result<LotteryBO> startLottery(HttpSession session) {
        return Result.success(lotteryService.startLottery(authService.getUserId(session)));
    }

    @GetMapping("/record")
    public Result<LotteryRecordVO> getLotteryRecord(HttpSession session) {
        String prize = lotteryService.getLotteryRecord(authService.getUserId(session));
        ExMatchUserVO userBO = authService.info(session);

        LotteryRecordVO lotteryRecordVO = new LotteryRecordVO()
                .setPrize(prize);
        if (userBO != null) {
            lotteryRecordVO.setPhone(userBO.getPhone());
            if (StringUtils.isNotBlank(userBO.getProvince()) && StringUtils.isNotBlank(userBO.getCity())
                    && StringUtils.isNotBlank(userBO.getRegion()) && StringUtils.isNotBlank(userBO.getAddress())) {
                if (StringUtils.equals(userBO.getProvince(), userBO.getCity())) {
                    lotteryRecordVO.setAddress(StringUtils.join(Lists.newArrayList(userBO.getCity(),
                            userBO.getRegion(), userBO.getAddress()), " "));
                } else {
                    lotteryRecordVO.setAddress(StringUtils.join(Lists.newArrayList(userBO.getProvince(), userBO.getCity(),
                            userBO.getRegion(), userBO.getAddress()), " "));
                }
            }
        }

        return Result.success(lotteryRecordVO);
    }

    @GetMapping("/prize/export")
    public void exportPrize() {
        //TODO 查询中奖表需要注意奖品库存的问题，库存为0，中奖表不插入最新记录
        lotteryService.exportPrize();
    }
}
